local LoadScene = class("LoadScene", cc.load("mvc").ViewBase)
local AniHelper = require("app.utils.AnimateHelper")

cc.exports.vm = cc.FileUtils:getInstance():getValueMapFromFile("config/chinese.plist")
cc.exports.win_size = cc.Director:getInstance():getWinSize()

function LoadScene:onCreate()
    local data = require("app.data.preload")
    local sfc = cc.SpriteFrameCache:getInstance()
    for i, v in ipairs(data) do
        if v.type == "plist" then
            sfc:addSpriteFrames(v.name .. ".plist", v.name .. ".pvr.ccz")
        elseif v.type == "image" then
            local sprite = cc.Sprite:create(v.name)
            sfc:addSpriteFrame(sprite:getSpriteFrame(), v.name)
        end
    end

    local sf = sfc:getSpriteFrameByName("popcap.png")
    self._icon = cc.Sprite:createWithSpriteFrame(sf)
    self._icon:setPosition(cc.p(win_size.width / 2, win_size.height / 2))
    self:addChild(self._icon)

    local function callback(node, data)
        cc.SimpleAudioEngine:getInstance():playBackgroundMusic("sounds/bg.mp3", true)
        node:removeFromParent()
        self._icon = nil
        self:initUI()
    end
    self._icon:runAction(cc.Sequence:create(cc.FadeOut:create(0), cc.FadeIn:create(1.5), cc.FadeOut:create(1.5), cc.CallFunc:create(callback), nil))
end

function LoadScene:initUI()
    local root = cc.CSLoader:createNode("scene/LoadScene.csb")
    root:setAnchorPoint(cc.p(0.5, 0.5))
    root:setPosition(win_size.width / 2, win_size.height / 2)
    self:addChild(root)

    self._start_btn = root:getChildByName("start_btn")
    self._start_btn:setTouchEnabled(false)

    local function onStartBtnTouch(sender, type)
        if type == ccui.TouchEventType.began then
            self._start_btn:setTitleColor(cc.c3b(205, 136, 58))
        elseif type == ccui.TouchEventType.ended then
            self._start_btn:setTitleColor(cc.c3b(225, 202, 93))
            local scene = self:getApp():createScene("MainScene")
            cc.Director:getInstance():replaceScene(cc.TransitionMoveInT:create(0.5, scene))
        end
        return true
    end
    self._start_btn:addTouchEventListener(onStartBtnTouch)

    self._load_slider = root:getChildByName("load_slider")
    self._load_slider:setPercent(0)
    self._load_slider:setTouchEnabled(false)

    local scheduler, timer

    local function loading(delta)
        self._load_slider:setPercent(self._load_slider:getPercent() + 2)
        if self._load_slider:getPercent() >= 100 then
            scheduler:unscheduleScriptEntry(timer)
            self._start_btn:setTitleText(vm["start_game"])
            self._start_btn:setTouchEnabled(true)
            self._load_slider:loadSlidBallTextureNormal("")
        end
    end

    scheduler = cc.Director:getInstance():getScheduler()
    timer = scheduler:scheduleScriptFunc(loading, 0.05, false)
end

return LoadScene
